//
//  PublishMsgViewController.m
//  家校互通
//
//  Created by 李赛 on 15/5/25.
//  Copyright (c) 2015年 姬鑫宇. All rights reserved.
//

#import "PublishMsgViewController.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "TextFieldTableViewCell.h"
#import "SelectLocalPicTableViewCell.h"
#import "PublishImageCollectionViewCell.h"
#import "BLParaEnumParamiter.h"
//#import "ZYQAssetPickerController.h"
#import "PMStyleOneTableViewCell.h"//没有后面segement
#import "PMStyleTwoTableViewCell.h"//存在选项segement
#import "PMSignUpTableViewCell.h"//单独报名的
#import "ChooseMsgVisibleView.h"//选择可见性
#import "VisibleStudentListViewController.h"
#import "JKImagePickerController.h"

#import "CoModel.h"

@interface PublishMsgViewController ()<UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UINavigationControllerDelegate,ChooseMsgVisibleViewDelegate,JKImagePickerControllerDelegate>

@property (nonatomic, retain) UITextView *textView;
@property (nonatomic, retain) UITextField *textField;
@property (nonatomic,retain) NSMutableArray *imageAssetArray;
@property (nonatomic, retain) NSMutableArray *titleListArray;
@property (nonatomic, retain) NSMutableArray *iconImageArray;

@property (nonatomic, assign) NSInteger type;
@property (nonatomic, strong) UISegmentedControl *segmentBtnLeave;
@property (nonatomic, strong) UISegmentedControl *segmentBtnComment;
@property (nonatomic, strong) UISegmentedControl *segmentBtnStatus;
@property (nonatomic, strong) UISegmentedControl *segmentBtnApply;
@property (nonatomic, copy) NSString *subTitleContent;
@property (nonatomic, strong, nullable) NSMutableString *userIdsString;
@property (nonatomic, strong, nullable) NSMutableString *userNameString;

@property (nonatomic, assign) NSInteger isVisiable;/**<其他成员是否可见，1全班可见，0部分可见*/
@end

@implementation PublishMsgViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"发布";
    _contentTableView.dataSource=self;
    _contentTableView.delegate=self;
    _contentTableView.estimatedRowHeight = 200;
    _contentTableView.fd_debugLogEnabled = YES;
    _imageAssetArray=[[NSMutableArray alloc]initWithCapacity:0];
    _isVisiable=1;//默认；
    _subTitleContent=@"班级所有人可见";
    if(_publishMsgStyle==PublishMsgStyleActivity)
    {
        _titleListArray=[NSMutableArray arrayWithObjects:@"谁可以看",@"状态",@"评论",@"报名", nil];
        
    }else if (_publishMsgStyle==PublishMsgStyleAskLeave)
    {
        _titleListArray=[NSMutableArray arrayWithObjects:@"请假条", nil];
        
    }
    else if (_publishMsgStyle==PublishMsgStyleNotice||_publishMsgStyle==PublishMsgStyleHomeWork)
    {
        _titleListArray=[NSMutableArray arrayWithObjects:@"谁可以看",@"状态",@"评论", nil];
        
    }else if (_publishMsgStyle==PublishMsgStylePraise)
    {
        _titleListArray=[NSMutableArray arrayWithObjects:@"被表彰的人",@"谁可以看",@"状态",@"评论", nil];
    }
    
    self.navigationItem.backBarButtonItem=[[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    
    UIButton *button=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 44, 44)];
    [button setTitle:@"发布" forState:UIControlStateNormal];
    [button.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(sendMsgBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:button];
    
    //    UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGestureAction:)];
    //    [_contentTableView addGestureRecognizer:tapGesture];
    
    // Do any additional setup after loading the view.
}
-(NSArray *)ImageDataArrayWithArray:(NSArray*)imageArray
{
    NSMutableArray *photoDataArray=[NSMutableArray new];
    for (JKAssets *asset in imageArray) {
        
        [photoDataArray addObject:asset.photo];
    }
    return photoDataArray;
}
#pragma mark  ---发布---
-(void)sendMsgBtnAction:(UIButton *)sender
{
    [_textView resignFirstResponder];
    [_textField resignFirstResponder];
    if ([_textField.text isEqualToString:@""] || _textField.text == nil) {
        HHAlertView *alertview = [[HHAlertView alloc] initWithTitle:@"警告" detailText:@"标题写点什么吧" addView:self.view cancelButtonTitle:nil otherButtonTitles:@[@"确定"]];
        alertview.mode = HHAlertViewModeWarning;
        [alertview showWithBlock:^(NSInteger index) {
            return;
        }];
    }
    if ([_textView.text isEqualToString:@""] || _textView.text == nil) {
        HHAlertView *alertview = [[HHAlertView alloc] initWithTitle:@"警告" detailText:@"写点什么内容吧" addView:self.view cancelButtonTitle:nil otherButtonTitles:@[@"确定"]];
        alertview.mode = HHAlertViewModeWarning;
        [alertview showWithBlock:^(NSInteger index) {
            return;
        }];
    }
    
    if (_publishMsgStyle==PublishMsgStyleAskLeave) {
        [CoModel leaveApply:^(BOOL result, NSString *failMessage,NSError *error) {
            if (result) {
                NSString *string = nil;
                if (_segmentBtnLeave.selectedSegmentIndex+1 == 1) {
                    string = @"请假条已经提交，请等待老师批准哦~!";
                }else if (_segmentBtnLeave.selectedSegmentIndex+1 == 2)
                    string = @"病假条已经提交，注意身体哦~！";
                HHAlertView *alertview = [[HHAlertView alloc] initWithTitle:@"成功" detailText:string addView:self.view cancelButtonTitle:nil otherButtonTitles:@[@"确定"]];
                alertview.mode = HHAlertViewModeSuccess;
                [alertview showWithBlock:^(NSInteger index) {
                    [self.navigationController popViewControllerAnimated:YES];
                }];
            }else{
                HHAlertView *alertview = [[HHAlertView alloc] initWithTitle:@"失败" detailText:failMessage addView:self.view cancelButtonTitle:nil otherButtonTitles:@[@"确定"]];
                alertview.mode = HHAlertViewModeError;
                [alertview showWithBlock:^(NSInteger index) {
                    [self.navigationController popViewControllerAnimated:YES];
                }];
            }
        } withType:_segmentBtnLeave.selectedSegmentIndex+1 withTitle:_textField.text withContent:_textView.text];
    }
    else
    {
        NSArray *imageAssetData;
        if (_imageAssetArray.count) {
            imageAssetData=[self ImageDataArrayWithArray:_imageAssetArray];
        }
        
        // 黑板报类型,1-作业,2-表彰,3-通知,4-活动,5-收费,6-公告
        NSInteger blackBoardType=0;
        NSInteger isTop=0;//是否置顶，0-不置顶，1-置顶
        NSInteger visibleRange=_isVisiable;//是否所有人可见,0-部分,1-所有人
        NSInteger isAllowComment=0;//是否允许评论,0-不允许,1-允许
        NSInteger registrationMode=0;//活动参与方式,1-直接参与,2-需要报名,当type=活动时有效
        NSInteger studentId=0;//被表彰的学生,当type='表彰'时有效
        NSString *userIds;//除创建者以外的其他班级成员，当visibleRange为“部分可见”时有效，格式id1,id2,id3
        userIds=_userIdsString;
        
    
        if (_publishMsgStyle==PublishMsgStyleHomeWork) {
            blackBoardType=1;
            isTop=_segmentBtnStatus.selectedSegmentIndex;
            isAllowComment=1-_segmentBtnComment.selectedSegmentIndex;
        
        }else if(_publishMsgStyle==PublishMsgStylePraise)//表彰
        {
            blackBoardType=2;
            isTop=_segmentBtnStatus.selectedSegmentIndex;
            isAllowComment=1-_segmentBtnComment.selectedSegmentIndex;
            studentId=[_userIdsString integerValue];
            
        }else if (_publishMsgStyle==PublishMsgStyleNotice)
        {
            blackBoardType=3;
            
            isTop=_segmentBtnStatus.selectedSegmentIndex;
            isAllowComment=1-_segmentBtnComment.selectedSegmentIndex;
   
            
        }else if (_publishMsgStyle==PublishMsgStyleActivity)
        {
            blackBoardType=4;
            isTop=_segmentBtnStatus.selectedSegmentIndex;
            isAllowComment=1-_segmentBtnComment.selectedSegmentIndex;
            registrationMode=_segmentBtnApply.selectedSegmentIndex+1;
            
        }else if(_publishMsgStyle==PublishMsgStyleChargeFee)
        {
            blackBoardType=5;
        }
        else if (_publishMsgStyle==PublishMsgStyleTotalNotice)//公告
        {
            blackBoardType=6;
        }
 
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [CoModel uploadImage:^(BOOL result, NSMutableArray *imageUrlList, NSError *error) {
            if (result) {
                [CoModel createNews:^(BOOL result, NSString *failMessage, NSError *error) {
                    if (result)
                    {
                        [MBProgressHUD hideHUDForView:self.view animated:YES];
                        HHAlertView *alertview = [[HHAlertView alloc] initWithTitle:@"成功" detailText:@"发表成功！" addView:self.view cancelButtonTitle:nil otherButtonTitles:@[@"确定"]];
                        alertview.mode = HHAlertViewModeSuccess;
                        [alertview showWithBlock:^(NSInteger index) {
                            
                            [[NSNotificationCenter defaultCenter] postNotificationName:@"BLACKBOARDCONNECT" object:nil];
                            [self.navigationController popViewControllerAnimated:YES];
                        }];
                    }
                    
                } withType:blackBoardType withTitle:_textField.text withContent:_textView.text withIsTop:isTop withImages:imageUrlList withVisibleRange:visibleRange withIsAllowComment:isAllowComment withStudentId:studentId withRegistrationMode:registrationMode withUsers:userIds];
            }
        } withImage:imageAssetData andType:2];
    
   
    }
}

#pragma mark -UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        return 2;
    }else
        return _titleListArray.count;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        if (indexPath.row==0) {
            TextFieldTableViewCell *vCell=[tableView dequeueReusableCellWithIdentifier:@"TextFieldTableViewCell" forIndexPath:indexPath];
            _textView=vCell.bodyTextView;
            _textField=vCell.headerTextField;
            return vCell;
        }else
        {
            SelectLocalPicTableViewCell *vCell=[tableView dequeueReusableCellWithIdentifier:@"SelectLocalPicTableViewCell" forIndexPath:indexPath];
            [vCell setCollectionViewDataSourceDelegate:self contentIndex:collectionViewTagForContentMImage];
            return vCell;
        }
        
    }else
    {
        NSString *titleString=[_titleListArray objectAtIndex:indexPath.row];
        if ([titleString isEqualToString:@"谁可以看"]) {
            PMStyleOneTableViewCell *vCell=[tableView dequeueReusableCellWithIdentifier:@"PMStyleOneTableViewCell" forIndexPath:indexPath];
            vCell.titleLB.text=titleString;
            vCell.iconImage.image=[UIImage imageNamed:titleString];
    
            vCell.subTitleLB.text=_subTitleContent;
            vCell.selectionStyle=UITableViewCellSelectionStyleNone;
            return vCell;
        }else if ([titleString isEqualToString:@"被表彰的人"])
        {
            PMStyleOneTableViewCell *vCell=[tableView dequeueReusableCellWithIdentifier:@"PMStyleOneTableViewCell" forIndexPath:indexPath];
            vCell.titleLB.text=titleString;
            vCell.iconImage.image=[UIImage imageNamed:titleString];
            vCell.subTitleLB.text=@"选择要表彰的同学";
            vCell.selectionStyle=UITableViewCellSelectionStyleNone;
            return vCell;
        }
        else if ([titleString isEqualToString:@"报名"])
        {
            PMSignUpTableViewCell *vCell=[tableView dequeueReusableCellWithIdentifier:@"PMSignUpTableViewCell" forIndexPath:indexPath];
            vCell.titleLB.text=titleString;
            vCell.iconImage.image=[UIImage imageNamed:titleString];
            _segmentBtnApply = vCell.segmentBtn;
            return vCell;
        }
        else
        {
            PMStyleTwoTableViewCell *vCell=[tableView dequeueReusableCellWithIdentifier:@"PMStyleTwoTableViewCell" forIndexPath:indexPath];
            vCell.titleLB.text=titleString;
            vCell.iconImage.image=[UIImage imageNamed:titleString];
            
            if ([titleString isEqualToString:@"状态"]) {
                
                [vCell.segmentBtn setTitle:@"普通" forSegmentAtIndex:0];
                [vCell.segmentBtn setTitle:@"置顶" forSegmentAtIndex:1];
                _segmentBtnStatus = vCell.segmentBtn;
            }else if ([titleString isEqualToString:@"评论"])
            {
                [vCell.segmentBtn setTitle:@"允许" forSegmentAtIndex:0];
                [vCell.segmentBtn setTitle:@"关闭" forSegmentAtIndex:1];
                _segmentBtnComment = vCell.segmentBtn;
            }else if ([titleString isEqualToString:@"请假条"])
            {
                [vCell.segmentBtn setTitle:@"事假" forSegmentAtIndex:0];
                [vCell.segmentBtn setTitle:@"病假" forSegmentAtIndex:1];
                _segmentBtnLeave = vCell.segmentBtn;
            }
            vCell.selectionStyle=UITableViewCellSelectionStyleNone;
            return vCell;
        }
        
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

#pragma mark -UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0)
    {
        if (indexPath.row==0) {
            return 150;
        }else
        {
            NSInteger imageCount;
            if (_imageAssetArray.count==9) {
                imageCount=_imageAssetArray.count;
            }
            else
            {
                imageCount=_imageAssetArray.count+1;
            }
            NSInteger indexRow=imageCount%3?imageCount/3+1:imageCount/3;
            return 10+75*indexRow+5*(indexRow-1);
        }
        
    }else
    {
        return 55;
    }
    
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section   // custom view for header. will be adjusted to default or specified header height
{
    return nil;
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [_textField resignFirstResponder];
    [_textView resignFirstResponder];
}
//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section   // custom view for footer. will be adjusted to default or specified footer height
//{
//
//}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}

// Called after the user changes the selection.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *titleString=[_titleListArray objectAtIndex:indexPath.row];
    if ([titleString isEqualToString:@"谁可以看"]) {
     
        NSArray *titleArray=[NSArray arrayWithObjects:@"本班所有人可见",@"指定部分人可见", nil];
        
        ChooseMsgVisibleView *chooseView=[[ChooseMsgVisibleView alloc]initWithFrame:CGRectMake((DSF_SCREENWIDTH-200)/2,(DSF_SCREENHEIGHT-(titleArray.count+1)*40)/2-44,  200, (titleArray.count+1)*40+10) withTitleArray:titleArray andHeaderTitle:titleString];
        chooseView.delegate=self;
        [chooseView presentViewFromVisibleView:self.view];
    }
    else if ([titleString isEqualToString:@"被表彰的人"])
    {
        
       PMStyleOneTableViewCell *cell=(PMStyleOneTableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
        VisibleStudentListViewController *vc=[self.storyboard instantiateViewControllerWithIdentifier:@"VisibleStudentListViewController"];
        __weak __typeof(self)weakSelf = self;
    
        SenderUserIdsDic block = ^(NSArray *studentList) {
            __strong __typeof(weakSelf) strongSelf = weakSelf;
            if (strongSelf) {
               strongSelf.userIdsString=[NSMutableString stringWithCapacity:0];
             strongSelf.userNameString=[NSMutableString stringWithCapacity:0];
                [studentList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                    ClazzStudents *model=(ClazzStudents*)obj;
                    if (idx==0)
                    {
                        [strongSelf.userIdsString appendString:[NSString stringWithFormat:@"%@",@(model.id)]];
                        [strongSelf.userNameString appendString:[NSString stringWithFormat:@"%@",model.name]];
                    }
                    else
                    {
                        [strongSelf.userIdsString appendString:[NSString stringWithFormat:@",%@",@(model.id)]];
                        [strongSelf.userNameString appendString:[NSString stringWithFormat:@",%@",model.name]];
                    }
                    
                }];
                cell.subTitleLB.text=strongSelf.userNameString;
                NSLog(@"%@",studentList);
            }
        };
        vc.senderUsers = block;

        vc.title=@"选择要表彰的人";
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark  ---ChooseMsgVisibleViewDelegate---
- (void)chooseMsgVisibleViewWithContent:(NSString *)content
{
     _subTitleContent=content;
    _isVisiable=1;
    if ([content isEqualToString:@"指定部分人可见"]) {
        VisibleStudentListViewController *vc=[self.storyboard instantiateViewControllerWithIdentifier:@"VisibleStudentListViewController"];
        vc.title=content;
        __weak __typeof(self)weakSelf = self;
        
        SenderUserIdsDic block = ^(NSArray *studentList) {
            __strong __typeof(weakSelf) strongSelf = weakSelf;
            if (strongSelf) {
                strongSelf.userIdsString=[NSMutableString stringWithCapacity:0];
                strongSelf.userNameString=[NSMutableString stringWithCapacity:0];
                [studentList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                    ClazzStudents *model=(ClazzStudents*)obj;
                    if (idx==0)
                    {
                        [strongSelf.userIdsString appendString:[NSString stringWithFormat:@"%@",@(model.id)]];
                        [strongSelf.userNameString appendString:[NSString stringWithFormat:@"%@",model.name]];
                        _isVisiable=0;
                    }
                    else
                    {
                        [strongSelf.userIdsString appendString:[NSString stringWithFormat:@",%@",@(model.id)]];
                        [strongSelf.userNameString appendString:[NSString stringWithFormat:@",%@",model.name]];
                    }
                    
                }];
            }
        };
        vc.senderUsers = block;
        [self.navigationController pushViewController:vc animated:YES];
    }
    [_contentTableView reloadData];
}

#pragma mark---UICollectionViewDataSource--
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (collectionView.tag==collectionViewTagForContentMImage) {
        if (_imageAssetArray.count==9) {
            return _imageAssetArray.count;
        }
        else
        {
            return _imageAssetArray.count+1;
        }
    }else
        return 0;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView.tag==collectionViewTagForContentMImage)
    {
        
        if (indexPath.row<_imageAssetArray.count) {
            PublishImageCollectionViewCell  *vCell=[collectionView dequeueReusableCellWithReuseIdentifier:@"PublishImageCollectionViewCell" forIndexPath:indexPath];
            
            if (_imageAssetArray.count)
            {
                
                JKAssets *asset=[_imageAssetArray objectAtIndex:indexPath.row];
                vCell.publishImage.image=asset.photo;
                
            }
            return vCell;
            
        }else
        {
            PublishImageCollectionViewCell  *vCell=[collectionView dequeueReusableCellWithReuseIdentifier:@"PublishImageCollectionViewCell" forIndexPath:indexPath];
            vCell.publishImage.image=[UIImage imageNamed:@"加号"];
            return vCell;
        }
        
    }
    return nil;
    
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    return nil;
}
#pragma mark---UICollectionViewDelegate--
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==_imageAssetArray.count) {
        JKImagePickerController *imagePickerController = [[JKImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.showsCancelButton = YES;
        imagePickerController.allowsMultipleSelection = YES;
        imagePickerController.minimumNumberOfSelection = 1;
        imagePickerController.maximumNumberOfSelection = 9;
        imagePickerController.selectedAssetArray = _imageAssetArray;
        UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:imagePickerController];
        [self presentViewController:navigationController animated:YES completion:NULL];
        
    }
    
}
#pragma mark - JKImagePickerControllerDelegate
- (void)imagePickerController:(JKImagePickerController *)imagePicker didSelectAsset:(JKAssets *)asset isSource:(BOOL)source
{
    [imagePicker dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)imagePickerController:(JKImagePickerController *)imagePicker didSelectAssets:(NSArray *)assets isSource:(BOOL)source
{
    _imageAssetArray=[NSMutableArray arrayWithArray:assets];
    [imagePicker dismissViewControllerAnimated:YES completion:^{
        [_contentTableView reloadData];
    }];
}

- (void)imagePickerControllerDidCancel:(JKImagePickerController *)imagePicker
{
    [imagePicker dismissViewControllerAnimated:YES completion:^{
        
    }];
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
